﻿using FTBS.Models.BLO;
using FTBS.Models.Entities;
using FTBS.Models.Entities.Concert;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Services;
using PagedList;

namespace FTBS.Controllers
{
    public class ScheduleController : Controller
    {
        private ScheduleBLO _scheduleBLO = new ScheduleBLO();
        private FilmBLO _filmBLO = new FilmBLO();
        private TheaterBLO _theaterBLO = new TheaterBLO();
        private RoomBLO _roomBLO = new RoomBLO();
        private ChairBLO _chairBLO = new ChairBLO();
        private ShowTimeBLO _showtimeBLO = new ShowTimeBLO();
        private PromotionBLO _promotionBLO = new PromotionBLO();
        private UserBLO _userBO = new UserBLO();
        private ChairBLO _bloChair = new ChairBLO();

        #region --- Booking Film ---

        #region Search By Film

        /// <summary>
        /// Load all schedule for choose film, theater, showtime for booking ticket
        /// </summary>
        /// <returns></returns>
        /// <author>VuongVT</author>
        public ActionResult Index()
        {
            if (this.Session["RoleName"] != null && this.Session["UserName"] != null && this.Session["Account"] != null && this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            var listFilm = _scheduleBLO.GetListOfFilmShowing();
            List<Theater> listTheaterOfFirstFilm = new List<Theater>();
            if (listFilm.Count > 0)
            {
                listTheaterOfFirstFilm = _scheduleBLO.GetListTheaterWhenChooseFilm(listFilm[0].FilmId);
            }
            ViewBag.ListTheater = listTheaterOfFirstFilm;

            List<ShowTimeConcertEntity> listShowTime = new List<ShowTimeConcertEntity>();
            if (listTheaterOfFirstFilm.Count > 0)
            {
                listShowTime = _scheduleBLO.GetListShowTimeWhenChooseTheater(listTheaterOfFirstFilm[0].TheaterId, listFilm[0].FilmId);
            }
            ViewBag.ListShowTime = listShowTime;

            SearchSchedule searchSchedule = new SearchSchedule();
            if (listFilm.Count() > 0 && listTheaterOfFirstFilm.Count() > 0)
            {
                searchSchedule.FilmId = listFilm[0].FilmId;
                searchSchedule.TheaterId = listTheaterOfFirstFilm[0].TheaterId;
            }

            ViewBag.SearchSchedule = searchSchedule;
            ViewBag.DeadLineForBooking = _theaterBLO.GetTheaterById(searchSchedule.TheaterId).DeadlineForBooking;

            ViewBag.IsFirstTimeLoad = true;

            return View(listFilm);
        }

        /// <summary>
        /// Partial show list of Theater
        /// </summary>
        /// <param name="filmId"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        public PartialViewResult TheatersByFilm(int filmId)
        {
            var listTheater = _scheduleBLO.GetListTheaterWhenChooseFilm(filmId);
            SearchSchedule searchSchedule = new SearchSchedule();
            searchSchedule.FilmId = filmId;
            ViewBag.SearchSchedule = searchSchedule;
            ViewBag.IsFirstTimeLoadTheater = false;
            if (listTheater.Count > 0)
            {
                ViewBag.FirstItemTheaterId = listTheater[0].TheaterId;
            }
            ViewBag.FirstItemFilmId = filmId;
            return PartialView(listTheater);
        }

        /// <summary>
        /// Partial show list of ShowTime
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        [WebMethod]
        public PartialViewResult ShowTimeOfTheater(SearchSchedule scheduleResult)
        {
            ViewBag.SearchSchedule = scheduleResult;
            ViewBag.DeadLineForBooking = _theaterBLO.GetTheaterById(scheduleResult.TheaterId).DeadlineForBooking;
            List<ShowTimeConcertEntity> listShowTime = new List<ShowTimeConcertEntity>();
            listShowTime = _scheduleBLO.GetListShowTimeWhenChooseTheater(scheduleResult.TheaterId, scheduleResult.FilmId);
            return PartialView(listShowTime);
        }

        #endregion

        #region Search By Theater

        /// <summary>
        /// Index for SearchByTheater
        /// </summary>
        /// <returns></returns>
        public ActionResult ScheduleTheater()
        {
            if (this.Session["RoleName"] != null && this.Session["UserName"] != null && this.Session["Account"] != null && this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            //List Theater for show in Theater Column
            List<Theater> listTheater = new List<Theater>();
            listTheater = _scheduleBLO.GetListTheaterForSearchByTheater();

            //List Film of First Theater in Theater Column
            List<Film> listFilmOfFirstTheater = new List<Film>();
            if (listTheater.Count > 0)
            {
                listFilmOfFirstTheater = _scheduleBLO.GetListFilmWhenChooseTheater(listTheater[0].TheaterId);
            }
            ViewBag.ListFilmOfFirstTheater = listFilmOfFirstTheater;

            List<ShowTimeConcertEntity> listShowTimeOfFirstFilm = new List<ShowTimeConcertEntity>();
            if (listFilmOfFirstTheater.Count > 0)
            {
                listShowTimeOfFirstFilm = _scheduleBLO.GetListShowTimeWhenChooseTheater(listTheater[0].TheaterId, listFilmOfFirstTheater[0].FilmId);
            }
            ViewBag.ListShowTimeOfFirstFilm = listShowTimeOfFirstFilm;

            SearchSchedule searchSchedule = new SearchSchedule();
            if (listTheater.Count() > 0 && listFilmOfFirstTheater.Count() > 0)
            {
                searchSchedule.TheaterId = listTheater[0].TheaterId;
                searchSchedule.FilmId = listFilmOfFirstTheater[0].FilmId;
            }
            ViewBag.SearchSchedule = searchSchedule;
            ViewBag.DeadLineForBooking = _theaterBLO.GetTheaterById(searchSchedule.TheaterId).DeadlineForBooking;

            ViewBag.IsFirstTimeLoad = true;

            return View(listTheater);
        }

        /// <summary>
        /// Partial show list of film when choose a theater
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns>PartialView FilmsByTheater</returns>
        /// <author>vuongvt</author>
        public PartialViewResult FilmsByTheater(int theaterId)
        {
            List<Film> listFilm = new List<Film>();
            listFilm = _scheduleBLO.GetListFilmWhenChooseTheater(theaterId);

            SearchSchedule searchSchedule = new SearchSchedule();
            searchSchedule.TheaterId = theaterId;
            ViewBag.SearchSchedule = searchSchedule;
            ViewBag.IsFirstTimeLoadFilm = false;
            if (listFilm.Count > 0)
            {
                ViewBag.FirstItemFilmId = listFilm[0].FilmId;
            }
            ViewBag.FirstItemTheaterId = theaterId;
            return PartialView(listFilm);
        }

        /// <summary>
        /// Partial show list of ShowTime
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        [WebMethod]
        public PartialViewResult ShowTimeOfFilm(SearchSchedule scheduleResult)
        {
            ViewBag.SearchSchedule = scheduleResult;
            ViewBag.DeadLineForBooking = _theaterBLO.GetTheaterById(scheduleResult.TheaterId).DeadlineForBooking;
            List<ShowTimeConcertEntity> listShowTime = new List<ShowTimeConcertEntity>();
            listShowTime = _scheduleBLO.GetListShowTimeWhenChooseTheater(scheduleResult.TheaterId, scheduleResult.FilmId);
            return PartialView(listShowTime);
        }

        #endregion


        /// <summary>
        /// Redirect to CheckOut to booking a film ticket
        /// </summary>
        /// <param name="showtimeId"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        public ActionResult BookingAFilmTicket(int showtimeId, int filmId, int theaterId, int roomId, int scheduleId)
        {
            if (this.Session["RoleName"] != null && this.Session["UserName"] != null && this.Session["Account"] != null && this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            SearchSchedule searchSchedule = new SearchSchedule();
            searchSchedule.FilmId = filmId;
            searchSchedule.TheaterId = theaterId;
            searchSchedule.ShowTimeId = showtimeId;
            searchSchedule.User = new User();
            searchSchedule.User.UserName = this.Session["UserName"] as string;
            searchSchedule.RoomId = roomId;

            //int scheduleId = _scheduleBLO.GetScheduleId(searchSchedule.FilmId, searchSchedule.RoomId, searchSchedule.ShowTimeId, searchSchedule.TheaterId);
            searchSchedule.ScheduleId = scheduleId;
           
            Session["SearchSchedule"] = searchSchedule;
            return RedirectToAction("Index", "CheckOut", searchSchedule);
        }
        
        /// <summary>
        /// Find a right schedule with input data and return to booking page
        /// </summary>
        /// <param name="showtimeId"></param>
        /// <param name="filmId"></param>
        /// <param name="theaterId"></param>
        /// <param name="date"></param>
        /// <returns></returns>  
        /// <author>vuongvt</author>
        public ActionResult BookingATicket(int showtimeId, int filmId, int theaterId, string date)
        {
            if (this.Session["RoleName"] != null && this.Session["UserName"] != null && this.Session["Account"] != null && this.Session["RoleName"].ToString().Trim() != "Customer")
            {
                return Redirect("/Home/Announcement");
            }
            var arrayDate = date.Split('/');
            DateTime dateValue = new DateTime(int.Parse(arrayDate[2]), int.Parse(arrayDate[1]), int.Parse(arrayDate[0]));

            ShowTimeConcertEntity result = _scheduleBLO.SetUpFastBuy(theaterId, filmId, dateValue, showtimeId).FirstOrDefault();
            SearchSchedule searchSchedule = new SearchSchedule();
            searchSchedule.FilmId = filmId;
            searchSchedule.TheaterId = theaterId;
            searchSchedule.ShowTimeId = showtimeId;
            searchSchedule.User = new User();
            searchSchedule.User.UserName = this.Session["UserName"] as string;
            searchSchedule.RoomId = result.RoomId;

            //int scheduleId = _scheduleBLO.GetScheduleId(searchSchedule.FilmId, searchSchedule.RoomId, searchSchedule.ShowTimeId, searchSchedule.TheaterId);
            searchSchedule.ScheduleId = result.ScheduleId;              
            Session["SearchSchedule"] = searchSchedule;
            return RedirectToAction("Index", "CheckOut", searchSchedule);     
        }

        #endregion

        #region --- Manage Schedule ---

        public ActionResult ListSchedule(string sortOrder, string currentFilter, string searchString, int? page, bool? isSortDescending, string fromDate, string toDate)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            List<ScheduleConcertEntity> listScheduleToShow = new List<ScheduleConcertEntity>();
            List<ScheduleConcertEntity> listScheduleInformation = new List<ScheduleConcertEntity>();
            listScheduleInformation = _scheduleBLO.GetAllScheduleInfo();

            //List<string> listTheater = new List<string>();
            //foreach (var item in _theaterBLO.GetAllTheaterInfo())
            //{
            //    listTheater.Add(item.TheaterName);
            //}
            //ViewBag.ddlTheater = new SelectList(listTheater);

            //Variable for 2 datetime Picker
            var fromDateValue = DateTime.Today;
            var toDateValue = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.DaysInMonth(DateTime.Now.Year, DateTime.Now.Month));
            ViewBag.ToDate = toDateValue;
            ViewBag.FromDate = fromDateValue;

            if (fromDate == null && toDate == null)
            {
                foreach (var schedule in listScheduleInformation)
                {
                    if (schedule.Date >= fromDateValue && schedule.Date <= toDateValue)
                    {
                        listScheduleToShow.Add(schedule);
                    }
                }
            }
            else
            {
                // Specify exactly how to interpret the string.
                IFormatProvider culture = new System.Globalization.CultureInfo("vi-VN", true);

                foreach (var schedule in listScheduleInformation)
                {
                    //var showTimeOfSchedule = _showtimeBLO.GetShowTimeById(schedule.ShowTimeId);
                    if (schedule.Date >= DateTime.Parse(fromDate, culture, System.Globalization.DateTimeStyles.AssumeLocal)
                        && schedule.Date <= DateTime.Parse(toDate, culture, System.Globalization.DateTimeStyles.AssumeLocal))
                    {
                        listScheduleToShow.Add(schedule);
                    }
                }
                ViewBag.ToDate = DateTime.Parse(toDate, culture, System.Globalization.DateTimeStyles.AssumeLocal);
                ViewBag.FromDate = DateTime.Parse(fromDate, culture, System.Globalization.DateTimeStyles.AssumeLocal);
            }


            ViewBag.NameSortParm = "film_name_desc";
            ViewBag.CurrentSort = sortOrder;

            if (searchString != null)
            {
                page = 1;
            }
            else
            {
                searchString = currentFilter;
            }

            ViewBag.CurrentFilter = searchString;
            ViewBag.IsSortDes = false;

            if (!String.IsNullOrEmpty(searchString))
            {
                listScheduleToShow = listScheduleToShow.Where(schedule => schedule.FilmName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.Date.ToShortDateString().ToUpper().Contains(searchString.ToUpper())
                                  || schedule.TheaterName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.RoomName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.TimeForShow.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.PromotionName.ToUpper().Contains(searchString.ToUpper())
                                  || schedule.PeopleCreate.ToUpper().Contains(searchString.ToUpper())).ToList();
            }

            switch (sortOrder)
            {
                case "film_name_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.FilmName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.FilmName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "theater_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.TheaterName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.TheaterName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "room_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.RoomName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.RoomName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "date_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.Date).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.Date).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "time_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.TimeForShow).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.TimeForShow).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "promotion_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.PromotionName).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.PromotionName).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                case "people_desc":
                    if (isSortDescending == true)
                    {
                        listScheduleToShow = listScheduleToShow.OrderByDescending(schedule => schedule.PeopleCreate).ToList();
                        ViewBag.IsSortDes = false;
                    }
                    else
                    {
                        listScheduleToShow = listScheduleToShow.OrderBy(schedule => schedule.PeopleCreate).ToList();
                        ViewBag.IsSortDes = true;
                    }
                    break;
                default:
                    listScheduleInformation = listScheduleToShow.OrderByDescending(schedule => schedule.ScheduleId).ToList();
                    ViewBag.IsSortDes = false;
                    break;
            }

            int pageSize = 5;
            int pageNumber = (page ?? 1);

            return View(listScheduleToShow.ToPagedList(pageNumber, pageSize));
        }

        /// <summary>
        /// Redirect to CreateSchedule page. Send ViewBag to load Combobox
        /// </summary>
        /// <returns></returns>
        public ActionResult CreateSchedule()
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name");
            ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName");
            ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName");
            List<ShowTime> listShowTime = new List<ShowTime>();
            ViewBag.ListShowTime = new SelectList(listShowTime);

            List<Room> listStrRoom = new List<Room>();
            ViewBag.Room = new SelectList(listStrRoom);
            ViewBag.SettingValue = null;
            ViewBag.ShowTimeIdSelected = 0;
            return View();
        }

        /// <summary>
        /// Create a schedule film
        /// </summary>
        /// <param name="format"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        /// <date>3/3/2014</date>
        [HttpPost]
        public ActionResult CreateSchedule(Schedule schedule)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (ModelState.IsValid)
            {
                if (schedule.Date != DateTime.MinValue)
                {
                    var dateArray = schedule.Date.ToShortDateString().Split('/');
                    var day = Convert.ToInt32(dateArray[0]);
                    var month = Convert.ToInt32(dateArray[1]);
                    var year = Convert.ToInt32(dateArray[2]);
                    DateTime dateValue = new DateTime(year, month, day);
                    schedule.Date = dateValue;
                }
                

                if (schedule.PromotionId != null)
                {
                    if (!_scheduleBLO.IsValidatePromotion(schedule))
                    {
                        TempData["AlertPromotion"] = true;
                        ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                        ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                        ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);

                        ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                        ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(Convert.ToInt32(schedule.TheaterId));
                        ViewBag.SettingValue = _theaterBLO.GetTheaterById(schedule.TheaterId).DeadlineCreateTicket;
                        ViewBag.ShowTimeIdSelected = 0;
                        return View(schedule);
                    }
                }

                bool isExistSchedule = _scheduleBLO.IsExistSchedule(schedule.FilmId, schedule.RoomId, schedule.ShowTimeId, schedule.TheaterId, schedule.Date);
                if (!isExistSchedule)
                {
                    if (_scheduleBLO.IsScheduleSmallerThanDeadline(schedule))
                    {
                        TempData["IsSmallerThanDeadLine"] = true;                       
                        ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                        ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                        ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);

                        ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                        ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(Convert.ToInt32(schedule.TheaterId));
                        ViewBag.SettingValue = _theaterBLO.GetTheaterById(schedule.TheaterId).DeadlineCreateTicket;
                        ViewBag.ShowTimeIdSelected = 0;
                        return View(schedule);
                    }
                    else
                    {
                        var username = this.Session["UserName"] as string;
                        // Specify exactly how to interpret the string.
                        IFormatProvider culture = new System.Globalization.CultureInfo("vi-VN", true);
                        schedule.Date = DateTime.Parse(schedule.Date.ToShortDateString());

                        var result = _scheduleBLO.CreateSchedule(schedule, username);
                        if (result == false)
                        {
                            TempData["AlertMessageNotComplete"] = true;
                            ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                            ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                            ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);

                            ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                            ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(Convert.ToInt32(schedule.TheaterId));
                            ViewBag.SettingValue = _theaterBLO.GetTheaterById(schedule.TheaterId).DeadlineCreateTicket;
                            ViewBag.ShowTimeIdSelected = 0;
                            return View(schedule);
                        }
                        else
                        {
                            //If this is Comming film, redirect to Schedule Page
                            //If this is Showing film, redirect to Ticket Page
                            if (schedule.IsActive == false)
                            {
                                return RedirectToAction("ListSchedule");
                            }
                            else
                            {
                                return RedirectToAction("Index", "Ticket");
                            }
                        }
                    }
                }
                else
                {
                    TempData["AlertMessage"] = true;
                    ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                    ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                    ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);

                    ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                    ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(Convert.ToInt32(schedule.TheaterId));
                    ViewBag.SettingValue = _theaterBLO.GetTheaterById(schedule.TheaterId).DeadlineCreateTicket;
                    ViewBag.ShowTimeIdSelected = 0;
                    return View(schedule);
                }
            }
            else
            {
                ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);

                //If user didn't choose TheaterId -> Show listRoom, listShowTime empty
                //Else, show listRoom and listShowTime of TheaterId
                if (schedule.TheaterId != 0)
                {
                    ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                    ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(Convert.ToInt32(schedule.TheaterId));
                    ViewBag.SettingValue = _theaterBLO.GetTheaterById(schedule.TheaterId).DeadlineCreateTicket;
                }
                else
                {
                    List<ShowTime> listShowTime = new List<ShowTime>();
                    ViewBag.ListShowTime = new SelectList(listShowTime);

                    List<Room> listStrRoom = new List<Room>();
                    ViewBag.Room = new SelectList(listStrRoom);
                    ViewBag.SettingValue = null;
                }
                ViewBag.ShowTimeIdSelected = 0;
                return View(schedule);
            }
        }

        /// <summary>
        /// Redirect to EditSchedule page
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult EditSchedule(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_scheduleBLO.IsScheduleUsingAndBooked(id))
            {
                TempData["CanNotEdit"] = true;
                return RedirectToAction("ListSchedule");
            }
            else
            {
                Schedule schedule = _scheduleBLO.GetScheduleById(id);
                if (schedule == null)
                {
                    return HttpNotFound();
                }
                ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);
                ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(schedule.TheaterId);
                ViewBag.ShowTimeIdSelected = schedule.ShowTimeId;
                return View(schedule);
            }
        }

        /// <summary>
        /// Edit a schedule
        /// </summary>
        /// <param name="schedule"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditSchedule(Schedule schedule)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (ModelState.IsValid)
            {
                bool isExistSchedule = _scheduleBLO.IsExistScheduleForEdit(schedule.ScheduleId, schedule.FilmId, schedule.RoomId, schedule.ShowTimeId, schedule.TheaterId, schedule.Date);
                if (!isExistSchedule)
                {
                    var username = this.Session["UserName"] as string;
                    var oldSchedule = _scheduleBLO.GetScheduleById(schedule.ScheduleId);
                    bool isChangeTheaterOrRoom = false;
                    if (oldSchedule.TheaterId != schedule.TheaterId || oldSchedule.RoomId != schedule.RoomId)
                    {
                        isChangeTheaterOrRoom = true;
                    }
                    _scheduleBLO.EditSchedule(schedule, username, isChangeTheaterOrRoom);
                    return RedirectToAction("ListSchedule");
                }
                else
                {
                    TempData["AlertMessage"] = true;
                    ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                    ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                    ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);
                    ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                    ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(schedule.TheaterId);
                    ViewBag.ShowTimeIdSelected = schedule.ShowTimeId;
                    return View(schedule);
                }
            }
            else
            {
                ViewBag.Film = new SelectList(_filmBLO.LoadFilms(), "FilmId", "Name", schedule.FilmId);
                ViewBag.Theater = new SelectList(_theaterBLO.GetAllTheaterInfo(), "TheaterId", "TheaterName", schedule.TheaterId);
                ViewBag.Promotion = new SelectList(_promotionBLO.GetListPromotionForCreateSchedule(), "PromotionId", "PromotionName", schedule.PromotionId);
                ViewBag.Room = _roomBLO.GetSelectedListRoomByTheater(Convert.ToInt32(schedule.TheaterId));
                ViewBag.ListShowTime = _showtimeBLO.GetSelectListShowTimeByTheater(schedule.TheaterId);
                ViewBag.ShowTimeIdSelected = schedule.ShowTimeId;
                return View(schedule);
            }
        }

        /// <summary>
        /// Delete a Schedule
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        /// <author>vuongvt</author>
        /// <date>3/6/2014</date>
        [HttpDelete, ActionName("DeleteSchedule")]
        public ActionResult DeleteSchedule(int id = 0)
        {
            if (this.Session["RoleName"] == null || this.Session["UserName"] == null || this.Session["Account"] == null || this.Session["RoleName"].ToString().Trim() != "Staff")
            {
                return Redirect("/Home/Announcement");
            }
            if (_scheduleBLO.IsScheduleUsingAndBooked(id))
            {
                TempData["CanNotDelete"] = true;
                return RedirectToAction("ListSchedule");
            }
            else
            {
                Schedule schedule = _scheduleBLO.GetScheduleById(id);
                if (schedule == null)
                {
                    return HttpNotFound();
                }
                _scheduleBLO.DeleteSchedule(schedule);
                return RedirectToAction("ListSchedule");
            }
        }

        /// <summary>
        /// Load combobox Room when choose a Theater
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns></returns>
        public JsonResult GetRoomByTheaterJson(int theaterId)
        {
            if (theaterId > 0)
            {
                return Json(_roomBLO.GetSelectedListRoomByTheater(theaterId));
            }
            else
            {
                List<string> listStrRoom = new List<string>();
                return Json(new SelectList(listStrRoom));
            }
        }

        /// <summary>
        /// Load combobox ShowTime when choose a Theater
        /// </summary>
        /// <param name="theaterId"></param>
        /// <returns></returns>
        public JsonResult GetShowTimeByTheaterJson(int theaterId)
        {
            if (theaterId > 0)
            {
                return Json(_showtimeBLO.GetSelectListShowTimeByTheater(theaterId));
            }
            else
            {
                List<string> listStrShowtime = new List<string>();
                return Json(new SelectList(listStrShowtime));
            }
        }

        /// <summary>
        /// Load list showtime when choose theater
        /// </summary>
        /// <param name="theaterId"></param>
        /// <param name="showtimeId"></param>
        /// <returns></returns>
        /// <author>VuongVT</author>
        public PartialViewResult GetListShowTimeByTheater(int theaterId, int? showtimeId = 0)
        {
            List<ShowTime> listShowTime = new List<ShowTime>();
            ViewBag.ShowTimeIdSelected = showtimeId;
            if (theaterId > 0)
            {
                listShowTime = _showtimeBLO.GetListShowTimeByTheaterId(theaterId);
            }
            return PartialView(listShowTime);
        }


        #endregion
    }
}
